package com.henz.web.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class ConvertUtil {

	/**
	 * Map to Entity
	 * @param kind
	 * @param key
	 * @param paramMap
	 * @return
	 */
	public static Entity toEntity( 
		  String kind
		, String key
		, Map<String, Object> paramMap 
	){
		Entity returnValue = null;
		
		Key keyObj = null;
		
		if(paramMap.containsKey(key) && paramMap.get(key) != null){
			
			keyObj = KeyFactory.createKey(kind, String.valueOf(paramMap.get( key )) );
			returnValue = new Entity(kind, keyObj);
			
			Set<String> keyIt = null;
			keyIt = paramMap.keySet();
			
			for(String mapKey:keyIt){
				returnValue.setProperty(mapKey, paramMap.get( mapKey ));
			}
			
			returnValue.setProperty("date", new Date());
			
		}
		
		return returnValue;
	}
	
	public static Map<String, Object> toMap( 
		Entity entity
	){
		
		Map<String, Object> returnValue = null;
		Key key = entity.getKey();
		
		returnValue = new HashMap<String, Object>(entity.getProperties());
		returnValue.put("objKey", key.getId());
		
		return returnValue;
		
	}
}
